package com.luzhikun.myshopping.controller;

import com.luzhikun.myshopping.dao.ProductDao;
import com.luzhikun.myshopping.dao.impl.ProductDaoImpl;
import com.luzhikun.myshopping.domaim.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author Rookie Coder
 * @Description
 * @Date
 **/
@WebServlet("/show")
public class ShowServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ProductDao productDao=new ProductDaoImpl();
        // 获取到的当前页
        String pn = req.getParameter("pn");
        // 当前页
        int pageNow ;
        // 每页的行数
        int pageCount=3;
        // 总行数
        int pageRows;
        // 判断当前页是否为null
        pageNow=pn==null?0:Integer.valueOf(pn);
        // 判断当前页页数是否小于 0
        if (pageNow <=0){
               pageNow=1;
        }
        System.out.println("------------当前页--------------");
        System.out.println(pageNow);
        System.out.println("------------当前页--------------");
        pageRows = productDao.selectCount();
        // 总页数(总行数/每页的行数)
        int pages=pageRows%pageCount==1?pageRows/pageCount:pageRows/pageCount+1;
        if (pageNow>=pages){
            pageNow=pages;
        }
        System.out.println("----------总页数----------------");
        System.out.println(pages);
        System.out.println("--------------------------");
        req.setAttribute("pages",pages);
        List<Product> products = productDao.selectAllProduct(pageNow,pageCount);
        // 查询到的所有商品
        req.setAttribute("products",products);
        // 当前页
        req.setAttribute("pageNows",pageNow);
        req.getRequestDispatcher("main.jsp").forward(req,resp);

    }
}
